<template>
  <div class="box-analysis">
    <div class="box-controller">
      <div class="box-search">
        <div class="box-search-left">
          <el-form :inline="true" :model="formParam" style="width: 100%">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="角色名称:">
                  <el-input v-model="formParam.roleName" placeholder="请输入角色名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="角色描述:">
                  <el-input v-model="formParam.description" placeholder="请输入角色描述" clearable />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="状态:">
                  <el-select v-model="formParam.status" placeholder="请选择状态" clearable>
                    <el-option label="禁用" value="1" />
                    <el-option label="启用" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6" class="box-search-btn">
                <el-form-item>
                  <el-button type="primary" class="zdy-btn" @click="searchWay">查询</el-button>
                  <!-- 修改后的代码，添加点击事件 -->
                  <el-button class="zdy-btn" @click="resetForm">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="controller-page">
        <div class="card-table">
          <div class="card-total-txt">
            <span>共搜索到{{ total }}条数据</span>
          </div>
          <div class="btn-group-tool">
            <el-button type="primary" @click="addRoleWay">新增角色</el-button>
            <el-button type="primary" plain @click="batchEnable">批量启用</el-button>
            <el-button type="primary" plain @click="batchDisable">批量禁用</el-button>
          </div>
          <div class="btn-group-notice">
            <el-icon class="icon"><InfoFilled /></el-icon>
            <span class="txt">已选择</span>
            <span class="num">{{ multipleSelection.length }}</span>
            <span class="txt">项</span>
          </div>

          <div class="table-list">
            <el-table
              ref="multipleTableRef"
              :data="dataList"
              row-key="id"
              style="width: 100%"
              height="100%"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <!-- <el-table-column type="index" width="50" /> -->
              <el-table-column prop="id" align="left" label="角色ID" width="150" />
              <el-table-column prop="roleName" align="left" label="角色名称" width="150" />
              <el-table-column prop="description" align="left" label="角色描述" min-width="200" show-overflow-tooltip />
              <el-table-column align="left" label="创建时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column align="left" label="更新时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.updateTime) }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" align="left" label="角色状态" width="100">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    :active-value="0"
                    :inactive-value="1"
                    @change="switchChange($event, scope.row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column fixed="right" align="center" label="操作" min-width="120">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="viewRoleWay(scope.row)"> 查看 </el-button>
                  <el-divider direction="vertical" />
                  <el-button link type="primary" size="small" @click="editRoleWay(scope.row)"> 编辑 </el-button>
                  <el-divider direction="vertical" />
                  <!-- 绑定删除方法 -->
                  <el-button link type="danger" size="small" @click="deleteRoleWay(scope.row.id)"> 删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="card-pagination">
            <el-pagination
              :small="true"
              v-model:current-page="formParam.pageNum"
              v-model:page-size="formParam.pageSize"
              layout="total, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <addRoleDialog
      ref="addRoleDialogRef"
      v-model:visible="showDialog"
      :rowData="rowRoleData"
      :isReadonly="roleIsReadonly"
      :title="roleTitle"
      @saveBack="getRoleUserListFunc"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue"
import dayjs from "dayjs"
import {
  getRoleUserList,
  batchDisableRoles,
  batchEnableRoles,
  deleteRole,
  updateRoleStatus
} from "@/api/roleUser/index.js"
import { ElMessage, ElMessageBox } from "element-plus"

import addRoleDialog from "./components/addRoleDialog.vue"

const showDialog = ref(false) // 控制对话框的显示隐藏
const addRoleDialogRef = ref(null)

const rowRoleData = ref({}) // 用于传递数据给对话框组件
const roleTitle = ref("") // 用于传递数据给对话框组件
const roleIsReadonly = ref(false) // 用于传递数据给对话框组件

const formParam = reactive({
  roleName: "",
  description: "",
  status: "",
  pageNum: 1,
  pageSize: 10
})
const dataList = ref([])
const multipleSelection = ref([])
const total = ref(0)

const searchInpt = ref("")
function searchWay() {
  formParam.pageNum = 1
  formParam.pageSize = 10
  getRoleUserListFunc()
}
// 定义重置表单的方法
const resetForm = () => {
  // 重置表单参数到初始状态
  formParam.roleName = ""
  formParam.description = ""
  formParam.status = ""
  searchWay()
}

function handleSizeChange(val) {
  formParam.pageSize = val
  getRoleUserListFunc()
}

function handleCurrentChange(val) {
  formParam.pageNum = val
  getRoleUserListFunc()
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 定义一个方法在切换开关时更新状态
const switchChange = async (newStatus, data) => {
  try {
    // 调用更新角色状态接口
    await updateRoleStatus({
      id: data.id,
      status: newStatus
    })
    ElMessage.success("角色状态更新成功")
  } catch (error) {
    // 若更新失败，将开关状态回退到原来的状态
    data.status = newStatus === 0 ? 1 : 0
    ElMessage.error("角色状态更新失败，请稍后重试")
  }
}

async function getRoleUserListFunc() {
  let res = await getRoleUserList(formParam)
  if (res.code === 200 && res.data) {
    dataList.value = res.data.records
    total.value = res.data.total
  } else {
    dataList.value = []
    total.value = 0
  }
}

onMounted(() => {
  getRoleUserListFunc()
})

function viewRoleWay(row) {
  rowRoleData.value = row // 传递数据给对话框组件
  roleTitle.value = "查看角色" // 传递数据给对话框组件
  roleIsReadonly.value = true // 传递数据给对话框组件
  showDialog.value = true // 显示对话框
}

function addRoleWay() {
  rowRoleData.value = {} // 传递数据给对话框组件
  roleTitle.value = "新增角色" // 传递数据给对话框组件
  roleIsReadonly.value = false // 传递数据给对话框组件
  showDialog.value = true // 显示对话框
}
function editRoleWay(row) {
  roleTitle.value = "编辑角色" // 传递数据给对话框组件
  roleIsReadonly.value = false // 传递数据给对话框组件
  rowRoleData.value = row // 传递数据给对话框组件
  showDialog.value = true // 显示对话框
}
// 批量启用功能
const batchEnable = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请先选择要启用的角色")
    return
  }
  try {
    await ElMessageBox.confirm(
      `请注意是否要${multipleSelection.value.length}项角色批量启用，启用后所选全部角色的所有相关权限将启用！`,
      "批量启用",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        icon: "Warning"
      }
    )
    // 将选中角色的 id 提取为数组，再转换为逗号分隔的字符串
    const ids = multipleSelection.value.map((item) => item.id)
    await batchEnableRoles(ids)
    ElMessage.success("批量启用成功")
    getRoleUserListFunc() // 刷新列表
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量启用失败，请稍后重试")
    }
  }
}
// 批量禁用功能
const batchDisable = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请先选择要禁用的角色")
    return
  }
  try {
    // 弹出确认框
    await ElMessageBox.confirm(
      `请注意是否要${multipleSelection.value.length}项角色批量禁用，禁用后所选全部角色的所有相关权限将失效！`,
      "批量禁用",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        icon: "Warning"
      }
    )
    // 将选中角色的 id 提取为数组，再转换为逗号分隔的字符串
    const ids = multipleSelection.value.map((item) => item.id)
    await batchDisableRoles(ids)
    ElMessage.success("批量禁用成功")
    getRoleUserListFunc() // 刷新列表
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量禁用失败，请稍后重试")
    }
  }
}
// 删除单个角色方法
const deleteRoleWay = async (id) => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm(`请注意是否要删除此项角色，删除后所选角色将失效！`, "删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "error",
      icon: "Warning"
    })
    // 调用批量删除接口，传入单个 id 组成的字符串
    await deleteRole({ id })
    ElMessage.success("删除成功")
    getRoleUserListFunc() // 刷新列表
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败，请稍后重试")
    }
  }
}
// 定义格式化时间的方法
const formatDate = (date) => {
  if (date) {
    return dayjs(date).format("YYYY-MM-DD HH:mm:ss")
  }
  return ""
}
</script>
<style scoped lang="scss">
.box-analysis {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #f0f0f0;
  padding: 20px 20px 0 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .box-search {
    width: 100%;
    // height: 40px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    ::v-deep .box-search-left {
      width: auto;
      height: 100%;
      display: flex;
      flex: 1;
      align-items: center;
      box-sizing: border-box;
      .el-form-item {
        margin-bottom: 0;
      }
      .box-search-btn .el-form-item__content {
        width: 100%;
        display: flex;
        justify-content: end;
      }
      .el-form--inline .el-form-item {
        display: inline-flex;
        margin-right: 0;
        vertical-align: middle;
        width: 100%;
      }
    }
    .box-search-right {
      width: auto;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-left: 20px;
      box-sizing: border-box;
      ::v-deep .zdy-input {
        width: 264px;
        height: 34px;
        line-height: 34px;
        background: #ffffff;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        margin-right: -2px;
        .el-input__wrapper {
          border-radius: 2px 0 0 2px;
        }
      }
      ::v-deep .zdy-btn {
        width: 56px;
        height: 34px;
        line-height: 34px;
        border-radius: 0;
        border-radius: 0px 2px 2px 0px;
      }
    }
  }
  .box-controller {
    width: 100%;
    height: 100%;
    display: flex;
    flex: 1;
    background-color: #fff;
    padding: 15px 15px 10px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }
  .controller-page {
    width: 100%;
    flex: 1;
    overflow: hidden;
  }
}

.card-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
}
.card-total-txt {
  width: 100%;
  height: 20px;
  line-height: 20px;
  font-family:
    Microsoft YaHei,
    Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin: 10px 0 5px 0;
}
.btn-group-tool {
  width: 100%;
  height: 40px;
  line-height: 40px;
}
.btn-group-notice {
  width: 100%;
  height: 32px;
  line-height: 32px;
  background: #e6f1ff;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #0c7cff;
  padding: 0 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 5px 0;
  .icon {
    width: 16px;
    height: 16px;
    color: #0c7cff;
    margin-right: 5px;
  }
  .txt {
    font-family:
      Microsoft YaHei,
      Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  .num {
    padding: 0 3px;
    font-family: Helvetica, Helvetica;
    font-weight: bold;
    font-size: 16px;
    color: #0c7cff;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
}

.table-list {
  width: 100%;
  display: flex;
  flex: 1;
  box-sizing: border-box;
  overflow: hidden;
  ::v-deep .el-table {
    .el-table__header-wrapper {
      th {
        background-color: #f5f9fc !important;
        color: #333333;
      }
    }
    .el-table__body-wrapper {
      td {
        color: #333333;
      }
    }
  }
}

.card-pagination {
  width: 100%;
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  box-sizing: border-box;
}
</style>
